#pragma once
#include "Socket.hpp"
#include <functional>
using func = function<void(shared_ptr<Socket>& sock,INETADDR& client)>;
class TcpServer
{
public:
    TcpServer(uint16_t port,func fun)
        : _port(port), _listensockptr(make_unique<TcpSocket>()), _isrunning(false),_fun(fun)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            INETADDR client;
            auto sock = _listensockptr->Accept(&client);
            if (sock == nullptr)
            {
                continue;
            }
            pid_t id = fork();
            if (id < 0)
            {
                LOG(LogLevel::FATAL) << "fork erro";
                exit(FORK_ERRO);
            }
            else if (id == 0)
            {
                // child
                _listensockptr->Close();
                if(fork() > 0 )
                    exit(OK);
                _fun(sock, client);
                sock->Close();
                exit(OK);
            }
            else
            {
                // father
                sock->Close();
                pid_t rid = waitpid(id, nullptr, 0);
                
            }
        }
        _isrunning = false;
    }
    ~TcpServer() {}

private:
    uint16_t _port;
    unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    func _fun;
};